﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AlipayPay.Infrastructure.EntitiyExtensions
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ISqlSugarClient _sqlSugarClient;

        // 注入 sugar client 实例
        public UnitOfWork(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }
        // 保证每次 scope 访问，多个仓储类，都用一个 client 实例
        // 注意，不是单例模型！！！
        public ISqlSugarClient GetDbClient()
        {
            return _sqlSugarClient;
        }


        /// <summary>
        /// 开始事务
        /// </summary>
        /// <returns></returns>
        public async Task BeginTran()
        {
            await GetDbClient().Ado.BeginTranAsync();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CommitTran()
        {
            try
            {
                await GetDbClient().Ado.CommitTranAsync(); //
            }
            catch (Exception)
            {
                await GetDbClient().Ado.RollbackTranAsync();
            }

            return true;
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <returns></returns>
        public async Task RollBack()
        {
            await GetDbClient().Ado.RollbackTranAsync();
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CommitAsync()
        {
            var res = await GetDbClient().SaveQueuesAsync();
            if (res > 0)
            {
                return true;
            }
            return false;
        }

    }
}
